我們在撰寫多人連線遊戲的Code時,針對程式上的錯誤來源,其實很難去追查,在這裡我們要用到線程的原理,來幫助我們在程式上的除錯更有效率。
線程你可以把它想成是一個工廠裡的工人,在電腦裡每個線程會一個或多個一起完成一份工作,若今天越多工人一起分工完成一個工作,那當然工作完成的速度也會越快,但是今天這個工作如果出現了問題,也會很難去尋找錯誤的根源。
那今天為了避免多線程造成Netcode不好除錯的問題,我們需要把"一份工作",交給單一個工人(線程)去作處理。
我們需要在Server及Client都各自創建一個ThreadManager,把需要用單線程執行的方法,放入ExecuteOnMainThread執行。
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ThreadManager : MonoBehaviour
{
private static readonly List<Action> executeOnMainThread = new List<Action>();
private static readonly List<Action> executeCopiedOnMainThread = new List<Action>();
private static bool actionToExecuteOnMainThread = false;
private void FixedUpdate()
{
UpdateMain();
}
/// <summary>Sets an action to be executed on the main thread.</summary>
/// <param name="_action">The action to be executed on the main thread.</param>
public static void ExecuteOnMainThread(Action _action)
{
if (_action == null)
{
Console.WriteLine("No action to execute on main thread!");
return;
}
lock (executeOnMainThread)
{
executeOnMainThread.Add(_action);
actionToExecuteOnMainThread = true;
}
}
/// <summary>Executes all code meant to run on the main thread. NOTE: Call this ONLY from the main thread.</summary>
public static void UpdateMain()
{
if (actionToExecuteOnMainThread)
{
executeCopiedOnMainThread.Clear();
lock (executeOnMainThread)
{
executeCopiedOnMainThread.AddRange(executeOnMainThread);
executeOnMainThread.Clear();
actionToExecuteOnMainThread = false;
}
for (int i = 0; i < executeCopiedOnMainThread.Count; i++)
{
executeCopiedOnMainThread[i]();
}
}
}
}